package utils
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	public class CDTimer
	{
		private var fun:Function;
		private var time:Number;
        private var startTime:Number;
		//private var debugTime:Number
		private var timer:Timer;
		private var watchFun:Function;
		private var watcheTime:int=1000;
		public function CDTimer(time:Number,fun:Function)
		{
			//this.debugTime=debugTime;
			trace("开始时:",time/1000/60)
			if(time<0) return;
			startTime=getTimer();
		    this.time=time;
            this.fun=fun;
			timer =new Timer(time);
		    timer.addEventListener(TimerEvent.TIMER,onTimer);
		    timer.start();
		}
		public function dispose():void{
			timer.removeEventListener(TimerEvent.TIMER,onTimer);
			timer.stop();
			timer=null;
			this.fun=null;
			unWatch();
		}
		
		public function reset(time:Number):void{
			timer.removeEventListener(TimerEvent.TIMER,onTimer);
			timer.stop();

			timer =new Timer(time);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
			timer.start();
		}
		
		private function onTimer(e:TimerEvent):void{
			if(fun!=null) this.fun();
			Timer(e.currentTarget).stop();
			Timer(e.currentTarget).removeEventListener(TimerEvent.TIMER,onTimer)
		}
		
		private var watchTimer:Timer=new Timer(watcheTime);
        private function unWatch():void{
			if(watchTimer){
			    watchTimer.stop();
				watchTimer.removeEventListener(TimerEvent.TIMER,onTemp);
			}
			watchFun=null;
		}
		public function watch(fun:Function):void{
			//unWatch();
			watchFun=fun
			watchTimer.start();
			watchTimer.addEventListener(TimerEvent.TIMER,onTemp);
		}
		private function onTemp(e:Event):void{
			var t:Number=time-(getTimer()-startTime);//*debugTime;
			watchFun(t);
			if(t<=0){
				unWatch();
			}
		}
	}
}